<script setup lang="ts">
import { h, ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { NModal, NCard, NForm, NSpace, NFormItem, NInput, NButton, NDataTable, NPagination, NPopconfirm, useNotification } from 'naive-ui'
import type { FormInst, FormRules } from 'naive-ui'
import http from '@/tools/http'

import { useUserStore } from '@/stores/userStore'

const userStore = useUserStore()
const router = useRouter()

type RowData = {
    roleCode: string
    roleName?: string
    remark?: string
}

const roleTableColumns: any = [
    {
        title: "角色编码",
        key: "roleCode",
        width: 100
    }, {
        title: "角色名称",
        key: "roleName",
        width: 100
    }, {
        title: "备注",
        key: "remark",
        width: 200
    }, {
        title: "操作",
        key: "actions",
        width: 192,
        fixed: 'right',
        render(rowData: RowData, rowIndex: number) {
            return h(
                NSpace, null,
                () => [
                    userStore.hasAuth("auth") ? h(
                        NButton,
                        {
                            size: "small",
                            onclick: () => openRoleAuth(rowData)
                        },
                        { default: () => "权限" }
                    ) : null,
                    userStore.hasAuth("role:edit") ? h(
                        NButton,
                        {
                            size: "small",
                            onclick: () => openEditRole(rowData)
                        },
                        { default: () => "编辑" }
                    ) : null,
                    userStore.hasAuth("role:delete") ? h(
                        NPopconfirm,
                        {
                            onPositiveClick: (e: MouseEvent) => deleteRole()
                        },
                        {
                            trigger: () => {
                                return h(
                                    NButton,
                                    {
                                        size: "small",
                                        onclick: () => openDeleteRole(rowData)
                                    },
                                    { default: () => "删除" }
                                )
                            },
                            default: () => { return "确认删除？" }
                        }
                    ) : null
                ]
            )
        }
    }
]

const roleData = reactive<any>({
    list: [],
    pageNum: 1,
    pageSize: 10,
    pages: 1,
    total: 0
})

const roleSearchFormValue = reactive({
    pageNum: 1,
    pageSize: 10,
    roleCode: "",
    roleName: ""
})

onMounted(() => {
    pageRole()
})

const visiable = ref<boolean>(false)
const title = ref<string>("")
const formRef = ref<FormInst | null>(null)
const formData = reactive<RowData>({
    roleCode: "",
    roleName: "",
    remark: ""
})

const formRules: FormRules = ({
    roleCode: {
        required: true,
        message: '请输入角色编码',
        trigger: ['input']
    },
    roleName: {
        required: true,
        message: '请输入角色名称',
        trigger: ['input']
    }
})

function pageNumChange(pageNum: number) {
    roleSearchFormValue.pageNum = pageNum
    pageRole()
}

function pageSizeChange(pageSize: number) {
    roleSearchFormValue.pageSize = pageSize
    pageRole()
}

function openRoleAuth(row: RowData) {
    router.push({
        name: 'auth',
        query: { objId: row.roleCode, objType: "1" }
    })
}

function openAddRole() {
    visiable.value = true
    title.value = "添加角色信息"
    formData.roleCode = ""
    formData.roleName = ""
    formData.remark = ""
}

function openEditRole(row: RowData) {
    visiable.value = true
    title.value = "编辑角色信息"
    formData.roleCode = row.roleCode
    formData.roleName = row.roleName
    formData.remark = row.remark
}

function openDeleteRole(row: RowData) {
    formData.roleCode = row.roleCode
    formData.roleName = row.roleName
    formData.remark = row.remark
}

function submit() {
    formRef.value?.validate((errors) => {
        if (!errors) {
            if (title.value === "添加角色信息") {
                addRole()
            } else {
                updateRole()
            }
            visiable.value = false
        }
    })
}

function pageRole() {
    http.post("/role/page", roleSearchFormValue).then(({ data }) => {
        if (data.code === "0") {
            roleData.pageNum = data.data.pageNum
            roleData.pageSize = data.data.pageSize
            roleData.pages = data.data.pages
            roleData.total = data.data.total
            roleData.list.length = 0
            for (let i = 0; i < data.data.list.length; i++) {
                roleData.list.push(data.data.list[i])
            }
        }
    })
}

const notification = useNotification()

function addRole() {
    http.post("/role/add", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '添加成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageRole()
        }
    })
}

function updateRole() {
    http.post("/role/update", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '修改成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageRole()
        }
    })
}

function deleteRole() {
    http.post("/role/delete", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '删除成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageRole()
        }
    })
}
</script>

<template>
    <div id="flame-container">
        <div class="search">
            <n-form :model="roleSearchFormValue" inline label-placement="left">
                <n-form-item label="角色编码" path="roleCode">
                    <n-input v-model:value="roleSearchFormValue.roleCode" placeholder="请输入角色编码" clearable />
                </n-form-item>
                <n-form-item label="角色名称" path="roleId">
                    <n-input v-model:value="roleSearchFormValue.roleName" placeholder="请输入角色名称" clearable />
                </n-form-item>
                <n-form-item>
                    <n-button attr-type="button" @click="pageRole()">查询</n-button>
                </n-form-item>
            </n-form>
        </div>
        <div class="btn-group">
            <n-button v-if="userStore.hasAuth('role:add')" attr-type="button" @click="openAddRole()">新增</n-button>
        </div>
        <div class="data-table">
            <n-data-table :scroll-x="592" :scrollbar-props="{ trigger: 'none' }" style="height:100%" flex-height
                :columns="roleTableColumns" :data="roleData.list" :bordered="false" />
        </div>
        <div class="pagination">
            <n-pagination style="float:right" v-model:page="roleData.pageNum" :page-size="roleData.pageSize"
                :item-count="roleData.total" :page-sizes="[5, 10, 30, 50, 100]" :on-update-page="pageNumChange"
                :on-update-page-size="pageSizeChange" show-quick-jumper show-size-picker />
        </div>
    </div>
    <n-modal v-model:show="visiable">
        <n-card style="width: 400px" :title="title">
            <n-form ref="formRef" :model="formData" :rules="formRules" label-width="78px" label-placement="left"
                require-mark-placement="left">
                <n-form-item label="角色编码" path="roleCode">
                    <n-input v-model:value="formData.roleCode" :disabled="title === '编辑角色信息'" placeholder="请输入角色编码"
                        clearable />
                </n-form-item>
                <n-form-item label="角色名称" path="roleName">
                    <n-input v-model:value="formData.roleName" placeholder="请输入角色名称" clearable />
                </n-form-item>
                <n-form-item label="备注" path="remark">
                    <n-input v-model:value="formData.remark" placeholder="请输入备注" clearable />
                </n-form-item>
            </n-form>
            <template #footer>
                <n-space justify="end">
                    <n-button attr-type="button" @click="visiable = false">取消</n-button>
                    <n-button attr-type="button" @click="submit()">提交</n-button>
                </n-space>
            </template>
        </n-card>
    </n-modal>
</template>

<style scoped>
.display-flex-end {
    display: flex;
    width: 100%;
    justify-content: flex-end;
}
</style>